package servlet;

import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/blogSubmit")
public class BlogSubmit extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        if(session == null || session.getAttribute("user")==null){
            resp.setStatus(302);
            resp.sendRedirect("login.html");
            return;
        }

        req.setCharacterEncoding("utf8");
        // 1.判断数据是否合法
       String title = req.getParameter("title");
       String content = req.getParameter("content");
       if(title==null || content==null || title.length()==0 || content.length()==0){
           resp.setContentType("text/html;charset=utf8");
           resp.getWriter().write("当前的标题或正文为空");
           return;
       }
       // 2. 构造blog对象, (blogId,不需要设置,按自增 , postTime 不需要设置,按 now())
        Blog blog = new Blog();
        User user = (User) session.getAttribute("user");
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        BlogDao blogDao = new BlogDao();
        //3.插入到数据库
        blogDao.insert(blog);
        //4.跳转到列表页
        resp.setStatus(302);
        resp.sendRedirect("blog_list.html");
    }
}
